/*
 * Copyright 2009 Jamie Gennis
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.gwt.remoteaction.testing;

import static org.easymock.EasyMock.reportMatcher;

import java.util.ArrayDeque;
import java.util.Deque;

import org.easymock.IArgumentMatcher;

/**
 * An EasyMock argument matcher for saving an argument that was passed to a
 * mocked method.
 * 
 * Each instance of this class can save a single argument at a time.
 * 
 * @param <T> the type of the argument to save
 * @author jgennis
 */
public class SaveArgument<T> implements IArgumentMatcher {

  protected T savedArgument;

  protected Deque<Class<? extends T>> expectedClasses = new ArrayDeque<Class<? extends T>>();

  @SuppressWarnings("unchecked")
  public boolean matches(Object object) {
    Class<?> expectedClass = expectedClasses.peekFirst();
    if (expectedClass == null || !expectedClass.isAssignableFrom(object.getClass()))
      return false;
    expectedClasses.removeFirst();
    savedArgument = (T) object;
    return true;
  }

  public void appendTo(StringBuffer stringBuffer) {
    stringBuffer.append("save(" + expectedClasses.peekFirst().getName() + ")");
  }

  /**
   * Get the most saved argument that was most recently passed to this
   * SaveArgument instance.
   * 
   * @return the saved argument
   */
  public T getSavedArgument() {
    return savedArgument;
  }

  /**
   * Call this method at the location of the argument you would like to save in
   * the same way that you would call <code>EasyMock.isA</code>.
   * 
   * @param cls the class or interface to which the argument must be assignable
   * @return null
   */
  public T saveA(Class<? extends T> cls) {
    expectedClasses.addLast(cls);
    reportMatcher(this);
    return null;
  }
}
